package com.ctshk.rpc.order.tour.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.order.tour.code.*;
import com.ctshk.rpc.order.tour.constant.Constants;
import com.ctshk.rpc.order.tour.dto.*;
import com.ctshk.rpc.order.tour.entity.*;
import com.ctshk.rpc.order.tour.mapper.*;
import com.ctshk.rpc.order.tour.req.*;
import com.ctshk.rpc.order.tour.service.ISeriesOrderReceiptDetailsService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderService;
import com.ctshk.rpc.order.tour.util.Utils;
import com.ctshk.rpc.stamp.dto.LevyDTO;
import com.ctshk.rpc.stamp.req.LevyRequest;
import com.ctshk.rpc.stamp.service.ILevyService;
import com.ctshk.rpc.system.dto.MainDataTeaPartyPlaceDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.MainDataTeaPartyPlaceIdReq;
import com.ctshk.rpc.system.service.IMainDataTeaPartyPlaceService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.tour.dto.TripBasicInformationDTO;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleDTO;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleDataDTO;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleTeamRuleDTO;
import com.ctshk.rpc.tour.req.SeriesTripReq;
import com.ctshk.rpc.tour.req.TripSupplementReq;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import com.ctshk.rpc.tour.service.ISeriesTripService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.*;

/**
 * <p>
 * 收据明细表、每一笔收据，产生一个数据 服务实现类
 * </p>
 *
 * @author 谭响
 * @since 2021-02-20
 */
@DubboService
public class SeriesOrderReceiptDetailsServiceImpl extends ServiceImpl<SeriesOrderReceiptDetailsMapper, SeriesOrderReceiptDetails> implements ISeriesOrderReceiptDetailsService {

    @DubboReference
    private ISeriesTripScheduleService iSeriesTripScheduleService;

    @Autowired
    private SeriesOrderReceiptDetailsMapper seriesOrderReceiptDetailsMapper;

    @Autowired
    private SeriesOrderReceiptTouristMapper seriesOrderReceiptTouristMapper;

    @Autowired
    private SeriesOrderReceiptMapper seriesOrderReceiptMapper;

    @Autowired
    private SeriesOrderTouristOtherFeeMapper seriesOrderTouristOtherFeeMapper;

    @Autowired
    private SeriesOrderTouristFeeAdjustMapper seriesOrderTouristFeeAdjustMapper;

    @Autowired
    private SeriesOrderTouristInfoMapper seriesOrderTouristInfoMapper;

    @Autowired
    private SeriesOrderCollectionMapper seriesOrderCollectionMapper;

    @Autowired
    private SeriesOrderAmountStatisticsMapper seriesOrderAmountStatisticsMapper;

    @DubboReference
    private ISeriesTripService iSeriesTripService;

    @DubboReference
    private ILevyService iLevyService;

    @Autowired
    private SeriesOrderMapper seriesOrderMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    @DubboReference
    private ISysDepartmentService iSysDepartmentService;

    @DubboReference
    private IMainDataTeaPartyPlaceService iMainDataTeaPartyPlaceService;

    @Autowired
    private ISeriesOrderService iSeriesOrderService;

    /**
     * 预览
     */
    @Override
    public Result<SeriesOrderReceiptDetailsPreviewDTO> preview(SeriesOrderReceiptDetailsPreviewReq req) {
        SeriesOrderReceiptDetailsPreviewDTO detailsPreviewDTO = new SeriesOrderReceiptDetailsPreviewDTO();
        detailsPreviewDTO.setId(IdWorker.getId());
        detailsPreviewDTO.setOrderId(req.getOrderId());
        detailsPreviewDTO.setScheduleId(req.getScheduleId());
        detailsPreviewDTO.setDataSource(req.getDataSource());

        //获取团期，判断是否能下单
        SeriesTripScheduleDTO tripScheduleDTO = iSeriesTripScheduleService.getTripScheduleId(req.getScheduleId());
        if (tripScheduleDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripScheduleDataDTO seriesTripScheduleDataDTO = tripScheduleDTO.getSeriesTripScheduleDataDTO();
        if (seriesTripScheduleDataDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripScheduleTeamRuleDTO seriesTripScheduleTeamRuleDTO = tripScheduleDTO.getSeriesTripScheduleTeamRuleDTO();
        if (seriesTripScheduleTeamRuleDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        TripBasicInformationDTO tripBasicInformationDTO = iSeriesTripService.basicInformation(seriesTripScheduleDataDTO.getTripId());
        if (tripBasicInformationDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripReq seriesTripReq = tripBasicInformationDTO.getSeriesTripReq();
        if (seriesTripReq == null) {
            return Result.failed(SystemError.SYS_411);
        }
        TripSupplementReq tripSupplementReq = iSeriesTripService.tripSupplement(seriesTripScheduleDataDTO.getTripId());
        if (tripSupplementReq == null) {
            return Result.failed(SystemError.SYS_411);
        }

        List<SeriesOrderReceiptDetailsPreviewItemDTO> itemDTOList = new ArrayList<>();
        List<SeriesOrderReceiptDetailsPreviewRemarkDTO> remarkDTOList = new ArrayList<>();
        Set<Long> touristIdList = new HashSet<>();
        Long firstTouristId = null;
        List<SeriesOrderCollection> items = new ArrayList<>();
        if (Objects.equals(DataSourceCode.COLLECTION.getCode(), req.getDataSource())) {
            List<SeriesOrderCollection> collectionList = seriesOrderCollectionMapper.selectBatchIds(req.getIdList());
            for (int i = 0; i < collectionList.size(); i++) {
                SeriesOrderCollection collection = collectionList.get(i);
                if (Objects.equals(collection.getIsPrint(), ISCode.YES.getCode())) {
                    continue;
                }
                if (i == 0) {
                    firstTouristId = collection.getTouristId();
                }
                touristIdList.add(collection.getTouristId());

                items.add(collection);
            }
        } else if (Objects.equals(DataSourceCode.RECEIPT.getCode(), req.getDataSource())) {
            //收款
            for (Long id : req.getIdList()) {
                QueryWrapper<SeriesOrderCollection> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
                queryWrapper.lambda().eq(SeriesOrderCollection::getTouristId, id);
                queryWrapper.lambda().eq(SeriesOrderCollection::getIsPrint, ISCode.NO.getCode());
                queryWrapper.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
                List<SeriesOrderCollection> collectionList = seriesOrderCollectionMapper.selectList(queryWrapper);
                items.addAll(collectionList);
            }
            firstTouristId = req.getIdList().get(0);
            //游客id
            touristIdList.addAll(req.getIdList());
        }

        if (items.size() <= 0) {
            return Result.failed(SeriesOrderErrorCode.PRINT_LIMIT_ERROR);
        }

        //代收费用
        BigDecimal receiptCollectionFee = new BigDecimal(0);
        //调整费用
        BigDecimal receiptAdjustmentCost = new BigDecimal(0);
        //其他
        BigDecimal receiptOtherAmount = new BigDecimal(0);
        //团费
        BigDecimal receiptGroupFee = new BigDecimal(0);
        //總應付
        BigDecimal receiptTotalReceivables = new BigDecimal(0);
        //已付
        BigDecimal receiptPaidAmount = new BigDecimal(0);
        //現付
        BigDecimal receiptPayAmount = new BigDecimal(0);
        //餘款
        BigDecimal receiptRemainingAmount = new BigDecimal(0);

        Map<Long, SeriesOrderTouristInfo> cache = new HashMap<>();
        for (Long id : touristIdList) {
            SeriesOrderTouristInfo touristInfo = null;
            if (cache.get(id) == null) {
                touristInfo = seriesOrderTouristInfoMapper.selectById(id);
                cache.put(id, touristInfo);
            } else {
                touristInfo = cache.get(id);
            }
            if (touristInfo == null) {
                throw new BusinessException(SystemError.SYS_411);
            }

            //收款项
            SeriesOrderReceiptDetailsPreviewItemDTO itemDTO = EntityUtil.copy(
                    touristInfo, SeriesOrderReceiptDetailsPreviewItemDTO.class);
            itemDTO.setTouristId(id);
            itemDTO.setPaidAmount(touristInfo.getReceiptedAmount());

            //代收费用
            BigDecimal collectionFee = new BigDecimal(0);
            //调整费用
            BigDecimal adjustmentCost = new BigDecimal(0);
            //其他
            BigDecimal otherAmount = new BigDecimal(0);
            //团费
            BigDecimal groupFee = new BigDecimal(0);
            //總應付
            BigDecimal totalReceivables = new BigDecimal(0);
            //已付
            BigDecimal paidAmount = new BigDecimal(0);
            //現付
            BigDecimal payAmount = new BigDecimal(0);
            //餘款
            BigDecimal remainingAmount = new BigDecimal(0);
            for (SeriesOrderCollection item : items) {
                if (Objects.equals(item.getTouristId(), id)) {
                    payAmount = payAmount.add(item.getPaidInAmount());
                    //收款方式銀行優惠、優惠、積分作為減免項
                    if (Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())
                            || Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.POINTS.getCode())
                            || Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode())) {
                        otherAmount = otherAmount.subtract(item.getPaidInAmount());
                    }
                }
            }
            //和其中的折扣費用進行合計，算出總減免的金額
            //代收费用
            QueryWrapper<SeriesOrderTouristOtherFee> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.lambda().eq(SeriesOrderTouristOtherFee::getOrderId, req.getOrderId());
            queryWrapper4.lambda().eq(SeriesOrderTouristOtherFee::getTouristId, id);
            queryWrapper4.lambda().eq(SeriesOrderTouristOtherFee::getFeeType, SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode());
            queryWrapper4.lambda().eq(SeriesOrderTouristOtherFee::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristOtherFee> touristOtherFees = seriesOrderTouristOtherFeeMapper.selectList(queryWrapper4);
            for (SeriesOrderTouristOtherFee fee : touristOtherFees) {
                if (Objects.equals(fee.getFeeType(), SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode()) &&
                        Objects.equals(fee.getFeeName(), ConstantsCode.DISCOUNT.getMsg())) {
                    otherAmount = otherAmount.subtract(fee.getAmount());
                }
            }

            //現付 = 所有收款累计
            itemDTO.setPayAmount(payAmount);
            //餘數=總應付-已付-現付
            remainingAmount = itemDTO.getTotalReceivables().subtract(
                    touristInfo.getReceiptedAmount()).subtract(payAmount);
            itemDTO.setRemainingAmount(remainingAmount);
            itemDTOList.add(itemDTO);

            //代收费用
            receiptCollectionFee = receiptCollectionFee.add(collectionFee);
            //调整费用
            receiptAdjustmentCost = receiptAdjustmentCost.add(adjustmentCost);
            //其他
            receiptOtherAmount = receiptOtherAmount.add(otherAmount);
            //团费
            receiptGroupFee = receiptGroupFee.add(groupFee);
            //總應付
            receiptTotalReceivables = receiptTotalReceivables.add(totalReceivables);
            //已付
            receiptPaidAmount = receiptPaidAmount.add(paidAmount);
            //現付
            receiptPayAmount = receiptPayAmount.add(payAmount);
            //餘款
            receiptRemainingAmount = receiptRemainingAmount.add(remainingAmount);

            //备注
            SeriesOrderReceiptDetailsPreviewRemarkDTO remarkDTO = EntityUtil.copy(
                    touristInfo, SeriesOrderReceiptDetailsPreviewRemarkDTO.class);

            LocalDate now = LocalDate.now();
            Period between1 = null;
            Period between2 = null;
            Period between3 = null;
            if (touristInfo.getCertificateValidDate1() != null) {
                between1 = Period.between(now, touristInfo.getCertificateValidDate1());
            }
            if (touristInfo.getCertificateValidDate2() != null) {
                between2 = Period.between(now, touristInfo.getCertificateValidDate2());
            }
            if (touristInfo.getCertificateValidDate3() != null) {
                between3 = Period.between(now, touristInfo.getCertificateValidDate3());
            }
            if ((between1 != null && between1.getDays() <= 60) || (between2 != null && between2.getDays() <= 60) || (between3 != null && between3.getDays() <= 60)) {
                remarkDTO.setIsInsufficient(ISCode.YES.getCode());
            } else {
                remarkDTO.setIsInsufficient(ISCode.NO.getCode());
            }

            //备注项目
            List<SeriesOrderReceiptDetailsPreviewRemarkProjectDTO> projectDTOList = new ArrayList<>();

            //团费
            SeriesOrderReceiptDetailsPreviewRemarkProjectDTO groupProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
            groupProjectDTO.setName(ConstantsCode.GROUP_FEE.getMsg());
            groupProjectDTO.setAmount(touristInfo.getGroupFee());
            projectDTOList.add(groupProjectDTO);

            //代收费用
            QueryWrapper<SeriesOrderTouristOtherFee> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderTouristOtherFee::getOrderId, req.getOrderId());
            queryWrapper.lambda().eq(SeriesOrderTouristOtherFee::getTouristId, id);
            queryWrapper.lambda().and(object -> object.eq(SeriesOrderTouristOtherFee::getFeeType, SeriesOrderTouristOtherFeeFeeTypeCode.COLLECTION.getCode())
                    .or().eq(SeriesOrderTouristOtherFee::getFeeType, SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode()));
            queryWrapper.lambda().eq(SeriesOrderTouristOtherFee::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristOtherFee> collectionFeeList = seriesOrderTouristOtherFeeMapper.selectList(queryWrapper);
            for (SeriesOrderTouristOtherFee fee : collectionFeeList) {
                if (Objects.equals(fee.getFeeType(), SeriesOrderTouristOtherFeeFeeTypeCode.COLLECTION.getCode())) {
                    SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(fee.getFeeName());
                    remarkProjectDTO.setAmount(fee.getAmount());
                    projectDTOList.add(remarkProjectDTO);
                }
            }

            //调整费用
            QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SeriesOrderTouristFeeAdjust::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, id);
            queryWrapper2.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
            queryWrapper2.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristFeeAdjust> adjustFeeList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper2);
            for (SeriesOrderTouristFeeAdjust adjustFee : adjustFeeList) {
                SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                remarkProjectDTO.setName(adjustFee.getName());
                remarkProjectDTO.setAmount(adjustFee.getAmount());
                remarkProjectDTO.setPlusType(adjustFee.getPlusType());
                projectDTOList.add(remarkProjectDTO);
            }

            //其他
            QueryWrapper<SeriesOrderCollection> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
            queryWrapper3.lambda().eq(SeriesOrderCollection::getTouristId, id);
            queryWrapper3.lambda().and(object -> object.eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())
                    .or().eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.POINTS.getCode())
                    .or().eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode()));
            queryWrapper3.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderCollection> collectionList = seriesOrderCollectionMapper.selectList(queryWrapper3);
            for (SeriesOrderCollection collection : collectionList) {
                if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())) {
                    SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.BANK_PREFERENCE.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(PlusTypeCode.SUBTRACT.getCode());
                    projectDTOList.add(remarkProjectDTO);
                } else if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.POINTS.getCode())) {
                    SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.POINTS.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(PlusTypeCode.SUBTRACT.getCode());
                    projectDTOList.add(remarkProjectDTO);
                } else if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode())) {
                    SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.OPERATE_PROMOTION.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(PlusTypeCode.SUBTRACT.getCode());
                    projectDTOList.add(remarkProjectDTO);
                }
            }
            for (SeriesOrderTouristOtherFee fee : collectionFeeList) {
                if (Objects.equals(fee.getFeeType(), SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode()) &&
                        Objects.equals(fee.getFeeName(), ConstantsCode.DISCOUNT.getMsg())) {
                    SeriesOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new SeriesOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(fee.getFeeName());
                    remarkProjectDTO.setAmount(fee.getAmount());
                    remarkProjectDTO.setPlusType(PlusTypeCode.SUBTRACT.getCode());
                    projectDTOList.add(remarkProjectDTO);
                }
            }

            remarkDTO.setProjectList(projectDTOList);
            remarkDTOList.add(remarkDTO);
        }

        //付款方式
        Map<Long, SeriesOrderReceiptDetailsPreviewWayDTO> wayMap = new HashMap<>();
        List<Long> collectionIdList = new ArrayList<>();
        for (SeriesOrderCollection item : items) {
            SeriesOrderReceiptDetailsPreviewWayDTO wayDTO = wayMap.get(item.getCollectionWayId());
            if (wayDTO == null) {
                wayDTO = EntityUtil.copy(
                        item, SeriesOrderReceiptDetailsPreviewWayDTO.class);
                ArrayList<SeriesOrderReceiptDetailsPreviewWayItemDTO> wayItemDTOList = new ArrayList<>();
                SeriesOrderReceiptDetailsPreviewWayItemDTO wayItemDTO = EntityUtil.copy(
                        item, SeriesOrderReceiptDetailsPreviewWayItemDTO.class);
                wayItemDTOList.add(wayItemDTO);
                wayDTO.setItemList(wayItemDTOList);
                wayMap.put(item.getCollectionWayId(), wayDTO);
            } else {
                SeriesOrderReceiptDetailsPreviewWayItemDTO wayItemDTO = EntityUtil.copy(
                        item, SeriesOrderReceiptDetailsPreviewWayItemDTO.class);
                wayDTO.getItemList().add(wayItemDTO);
            }
            collectionIdList.add(item.getId());
        }
        List<SeriesOrderReceiptDetailsPreviewWayDTO> wayDTOList = new ArrayList<>();
        for (Long key : wayMap.keySet()) {
            wayDTOList.add(wayMap.get(key));
        }

        SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(firstTouristId);

        detailsPreviewDTO.setCustomerRights(seriesTripScheduleDataDTO.getCustomerRights());
        if(seriesTripScheduleTeamRuleDTO.getTeaPartyLocId() != null) {
            MainDataTeaPartyPlaceIdReq mainDataTeaPartyPlaceIdReq = new MainDataTeaPartyPlaceIdReq();
            mainDataTeaPartyPlaceIdReq.setId(seriesTripScheduleTeamRuleDTO.getTeaPartyLocId());
            MainDataTeaPartyPlaceDTO mainDataTeaPartyPlaceDTO = iMainDataTeaPartyPlaceService.query(mainDataTeaPartyPlaceIdReq);
            if (mainDataTeaPartyPlaceDTO != null) {
                detailsPreviewDTO.setTeaPartyLocName(mainDataTeaPartyPlaceDTO.getTeaPartyPlace());
            }
        }
        detailsPreviewDTO.setTeaPartyDate(seriesTripScheduleTeamRuleDTO.getTeaPartyDate());
        detailsPreviewDTO.setTeaPartyTime(seriesTripScheduleTeamRuleDTO.getTeaPartyTime());
//        detailsPreviewDTO.setCompanyNotes();
        if (StringUtils.isNotBlank(touristInfo.getEnSurname()) && StringUtils.isNotBlank(touristInfo.getEnName())) {
            if (StringUtils.isNotBlank(touristInfo.getCnSurname()) && StringUtils.isNotBlank(touristInfo.getCnName())) {
                detailsPreviewDTO.setTouristName(touristInfo.getEnSurname() + " " + touristInfo.getEnName() +
                        "(" + touristInfo.getCnSurname() + " " + touristInfo.getCnName() + ")");
            } else {
                detailsPreviewDTO.setTouristName(touristInfo.getEnSurname() + " " + touristInfo.getEnName());
            }
        } else {
            if (StringUtils.isNotBlank(touristInfo.getCnSurname()) && StringUtils.isNotBlank(touristInfo.getCnName())) {
                detailsPreviewDTO.setTouristName(touristInfo.getCnSurname() + " " + touristInfo.getCnName());
            }
        }

        UserDTO createUser = iSysUserService.loadUserInfo(req.getUserId(), 1);
        if (createUser != null) {
            SysDepartmentDTO sysDepartmentDTO = iSysDepartmentService.queryByUserId(createUser.getId());
            if (sysDepartmentDTO != null) {
                detailsPreviewDTO.setAgent(sysDepartmentDTO.getDeptCode());
            }
        }

        SeriesOrder dbOrder = seriesOrderMapper.selectById(req.getOrderId());
        if (dbOrder == null) {
            return Result.failed(SystemError.SYS_411);
        }

        LocalDate mantissaDate = dbOrder.getGmtCreate().toLocalDate().plusDays(seriesTripScheduleTeamRuleDTO.getDeliveryDays());
        detailsPreviewDTO.setMantissaDate(mantissaDate);
        detailsPreviewDTO.setTourCode(tripScheduleDTO.getTripNumber());
        detailsPreviewDTO.setDays(seriesTripScheduleDataDTO.getTravelDays());
        detailsPreviewDTO.setDepDate(Utils.getDayAndWeek(tripScheduleDTO.getDepartureDate().atStartOfDay()));
        detailsPreviewDTO.setDepartureDate(tripScheduleDTO.getDepartureDate());
        detailsPreviewDTO.setRoute(seriesTripScheduleDataDTO.getTitle());
        detailsPreviewDTO.setEnquiryNo(Utils.getRandom6());
        detailsPreviewDTO.setEnquiryTimeTel(Constants.QUERY_TIME);
        detailsPreviewDTO.setItemList(itemDTOList);
        detailsPreviewDTO.setWayList(wayDTOList);
        detailsPreviewDTO.setRemarkList(remarkDTOList);
        detailsPreviewDTO.setCollectionIdList(collectionIdList);
        detailsPreviewDTO.setReceiptNumber(iSeriesOrderService.getReceiptNumberSale(req.getUserId()));
        //代收费用
        detailsPreviewDTO.setCollectionFee(receiptCollectionFee);
        //调整费用
        detailsPreviewDTO.setAdjustmentCost(receiptAdjustmentCost);
        //其他
        detailsPreviewDTO.setOtherAmount(receiptOtherAmount);
        //团费
        detailsPreviewDTO.setGroupFee(receiptGroupFee);
        //總應付
        detailsPreviewDTO.setTotalReceivables(receiptTotalReceivables);
        //已付
        detailsPreviewDTO.setPaidAmount(receiptPaidAmount);
        //現付
        detailsPreviewDTO.setPayAmount(receiptPayAmount);
        //餘款
        detailsPreviewDTO.setRemainingAmount(receiptRemainingAmount);
        detailsPreviewDTO.setTripSupplementRemark(tripSupplementReq.getRemark());
        detailsPreviewDTO.setTripSupplementSignNotice(tripSupplementReq.getSignNotice());
        detailsPreviewDTO.setTripSupplementTourFeeExclude(tripSupplementReq.getTourFeeExclude());
        detailsPreviewDTO.setTripSupplementTourFeeInclude(tripSupplementReq.getTourFeeInclude());
        detailsPreviewDTO.setMobile(touristInfo.getMobile());
        detailsPreviewDTO.setDeparturePlaceId(seriesTripReq.getDeparturePlaceId());
        detailsPreviewDTO.setDestinationId(seriesTripReq.getDestinationId());
        return Result.success(detailsPreviewDTO);
    }

    /**
     * 详情
     */
    /*@Override
    public Result detail(SeriesOrderReceiptDetailsDetailReq req) {
        if (Objects.equals(ReceiptTypeCode.SALE.getCode(), req.getReceiptType())) {
            SeriesOrderReceiptDetails receiptDetails = getById(req.getId());
            SeriesOrderReceiptDetailsPreviewDTO dto = null;
            if (receiptDetails != null && StringUtils.isNotBlank(receiptDetails.getReceipJson())) {
                dto = JSON.parseObject(receiptDetails.getReceipJson(), SeriesOrderReceiptDetailsPreviewDTO.class);
                if (dto != null) {
                    dto.setId(receiptDetails.getId());
                    dto.setOrderId(receiptDetails.getOrderId());
                    dto.setScheduleId(receiptDetails.getScheduleId());
                    dto.setTouristName(receiptDetails.getTouristName());
                    dto.setCustomerRights(receiptDetails.getCustomerRights());
                    dto.setCompanyNotes(receiptDetails.getCompanyNotes());
                    dto.setTeaPartyLocName(receiptDetails.getTeaPartyLocName());
                    dto.setTeaPartyDate(receiptDetails.getTeaPartyDate());
                    dto.setTeaPartyTime(receiptDetails.getTeaPartyTime());
                }
            }
            return Result.success(dto);
        } else if (Objects.equals(ReceiptTypeCode.INSURANCE.getCode(), req.getReceiptType())) {
            SeriesOrderReceiptDetails receiptDetails = getById(req.getId());
            SeriesOrderReceiptDetailsPreviewInsuranceDTO dto = null;
            if (receiptDetails != null && StringUtils.isNotBlank(receiptDetails.getReceipJson())) {
                dto = JSON.parseObject(receiptDetails.getReceipJson(), SeriesOrderReceiptDetailsPreviewInsuranceDTO.class);
                if (dto != null) {
                    dto.setId(receiptDetails.getId());
                    dto.setOrderId(receiptDetails.getOrderId());
                    dto.setScheduleId(receiptDetails.getScheduleId());
                    dto.setTouristName(receiptDetails.getTouristName());
                }
            }
            return Result.success(dto);
        }
        return Result.failed(SystemError.SYS_411);
    }*/

    /**
     * 添加
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(SeriesOrderReceiptDetailsAddReq req) {
        if (req.getId() == null) {
            return Result.success(SystemError.SYS_402);
        }
        SeriesOrderReceiptDetails dbReceiptDetails = getById(req.getId());
        if (dbReceiptDetails == null) {
            SeriesOrderReceipt saveObject = EntityUtil.copy(req, SeriesOrderReceipt.class);
            saveObject.setId(IdWorker.getId());
            saveObject.setReceiptHeader(req.getTouristName());
            saveObject.setReceiptType(ReceiptTypeCode.SALE.getCode());
            saveObject.setReceiptAmount(req.getPayAmount());
            saveObject.setIncludeTouristNum(req.getItemList().size());
            saveObject.setReceiptStatus(ReceiptStatusCode.VALID.getCode());
            LocalDateTime now = LocalDateTime.now();
            saveObject.setCreateTime(now);
            saveObject.setGmtCreate(now);
            saveObject.setGmtModified(now);
            saveObject.setCreateId(req.getUserId());
            saveObject.setModifiedId(req.getUserId());
            saveObject.setIsDeleted(IsDeletedCode.NO.getCode());
            seriesOrderReceiptMapper.insert(saveObject);

            BigDecimal stampDutyAmount = new BigDecimal(0);
            for (SeriesOrderReceiptDetailsAddItemReq item : req.getItemList()) {
                SeriesOrderReceiptTourist receiptTourist = new SeriesOrderReceiptTourist();
                receiptTourist.setReceiptId(saveObject.getId());
                receiptTourist.setOrderId(saveObject.getOrderId());
                receiptTourist.setTouristId(item.getTouristId());
                receiptTourist.setCreateId(req.getUserId());
                receiptTourist.setModifiedId(req.getUserId());
                receiptTourist.setIsDeleted(IsDeletedCode.NO.getCode());
                receiptTourist.setReceiptAmount(item.getPayAmount());
                receiptTourist.setGmtModified(now);
                receiptTourist.setGmtCreate(now);
                receiptTourist.setIsReceiptCalculated(ISCode.NO.getCode());
                seriesOrderReceiptTouristMapper.insert(receiptTourist);

                if(Objects.equals(Constants.AREA_HK, req.getDeparturePlaceId())) {
                    SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(item.getTouristId());
                    if (Objects.equals(touristInfo.getIsReceiptCalculated(), ISCode.NO.getCode())) {
                        stampDutyAmount = stampDutyAmount.add((item.getPayAmount().subtract(item.getCollectionFee())).multiply(
                                new BigDecimal(Constants.STAMP_DUTY_RATIO)));

                        receiptTourist.setIsReceiptCalculated(ISCode.YES.getCode());

                        touristInfo.setIsReceiptCalculated(ISCode.YES.getCode());
                        seriesOrderTouristInfoMapper.updateById(touristInfo);
                    } else if (Objects.equals(touristInfo.getIsReceiptCalculated(), ISCode.YES.getCode())) {
                        stampDutyAmount = stampDutyAmount.add(item.getPayAmount().multiply(
                                new BigDecimal(Constants.STAMP_DUTY_RATIO)));
                    }
                }
            }

            List<SeriesOrderCollection> collectionList = seriesOrderCollectionMapper.selectBatchIds(req.getCollectionIdList());
            for (SeriesOrderCollection collection : collectionList) {
                if (Objects.equals(ISCode.YES.getCode(), collection.getIsPrint())) {
                    throw new BusinessException(SeriesOrderErrorCode.PRINT_LIMIT_ERROR);
                }
                collection.setIsPrint(ISCode.YES.getCode());
                seriesOrderCollectionMapper.updateById(collection);
            }

            if(Objects.equals(Constants.AREA_HK, req.getDeparturePlaceId()) &&
                    stampDutyAmount.compareTo(new BigDecimal(0)) > 0) {
                LevyRequest levyRequest = new LevyRequest();
                levyRequest.setReceiptNumber(req.getReceiptNumber());
                levyRequest.setNameOfTravelerPayer(req.getTouristName());
                levyRequest.setDepartureDate(Utils.getDateString(req.getDepartureDate(), Utils.yyyy_MM_dd));
                DecimalFormat nf = new DecimalFormat(Utils.DECIMAL_POINT4);
                levyRequest.setPremiumReceived(nf.format(stampDutyAmount));
                levyRequest.setLast4DigitOfContactPhoneNumber(req.getMobile().substring(req.getMobile().length() - 4));
                Result<LevyDTO> levyDTOResult = iLevyService.levyEFrank(levyRequest);
                if (!levyDTOResult.isSuccess() || levyDTOResult.getData() == null) {
                    throw new BusinessException(SystemError.SYS_500);
                }
                LevyDTO levyDTO = levyDTOResult.getData();
                req.setStampDutyPic(Base64.getEncoder().encodeToString(levyDTO.getLevystamp()));
            }

            SeriesOrderReceiptDetails receiptDetails = new SeriesOrderReceiptDetails();
            receiptDetails.setId(req.getId());
            receiptDetails.setOrderId(saveObject.getOrderId());
            receiptDetails.setScheduleId(saveObject.getScheduleId());
            receiptDetails.setReceiptId(saveObject.getId());
            receiptDetails.setReceiptType(saveObject.getReceiptType());
            receiptDetails.setTouristName(req.getTouristName());
            receiptDetails.setCustomerRights(req.getCustomerRights());
            receiptDetails.setCompanyNotes(req.getCompanyNotes());
            receiptDetails.setReceipJson(JSON.toJSONString(req));
            receiptDetails.setReceiptStatus(saveObject.getReceiptStatus());
            receiptDetails.setTeaPartyLocName(req.getTeaPartyLocName());
            receiptDetails.setTeaPartyDate(req.getTeaPartyDate());
            receiptDetails.setTeaPartyTime(req.getTeaPartyTime());
            save(receiptDetails);

        }
        return Result.success(req);
    }

    /**
     * 重印
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result redo(SeriesOrderReceiptDetailsRedoReq req) {
        SeriesOrderReceiptDetails receiptDetails = getById(req.getId());
        if (receiptDetails == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesOrderReceipt dbReceipt = seriesOrderReceiptMapper.selectById(receiptDetails.getReceiptId());
        if (dbReceipt == null) {
            return Result.failed(SystemError.SYS_411);
        }
        if (!Objects.equals(dbReceipt.getReceiptStatus(), ReceiptStatusCode.VALID.getCode())) {
            return Result.failed(SeriesOrderErrorCode.STATUS_ERROR);
        }
        SeriesOrderReceiptDetailsPreviewDTO dto = null;
        if (!Objects.equals(req.getTouristName(), receiptDetails.getTouristName())) {
            if (StringUtils.isBlank(receiptDetails.getReceipJson())) {
                return Result.failed(SystemError.SYS_411);
            }
            dto = JSON.parseObject(receiptDetails.getReceipJson(), SeriesOrderReceiptDetailsPreviewDTO.class);
            if (dto == null) {
                return Result.failed(SystemError.SYS_411);
            }
            if (CollectionUtils.isEmpty(dto.getCollectionIdList())) {
                return Result.failed(SystemError.SYS_500);
            }

            LocalDateTime now = LocalDateTime.now();
            dbReceipt.setVoidTime(now);
            dbReceipt.setGmtModified(now);
            dbReceipt.setModifiedId(req.getUserId());
            dbReceipt.setReceiptStatus(ReceiptStatusCode.INVALID.getCode());
            seriesOrderReceiptMapper.updateById(dbReceipt);

            QueryWrapper<SeriesOrderReceiptTourist> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getReceiptId, dbReceipt.getId());
            queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getOrderId, dbReceipt.getOrderId());
            List<SeriesOrderReceiptTourist> receiptTouristList = seriesOrderReceiptTouristMapper.selectList(queryWrapper);
            //游客统计
            for (SeriesOrderReceiptTourist receiptTourist : receiptTouristList) {
                if (Objects.equals(receiptTourist.getIsReceiptCalculated(), ISCode.NO.getCode())) {
                    continue;
                }
                SeriesOrderTouristInfo touristInfo = new SeriesOrderTouristInfo();
                touristInfo.setId(receiptTourist.getTouristId());
                touristInfo.setIsReceiptCalculated(ISCode.NO.getCode());
                seriesOrderTouristInfoMapper.updateById(touristInfo);
            }

            //将收款明细设置成打印否
            for (Long id : dto.getCollectionIdList()) {
                SeriesOrderCollection collection  = new SeriesOrderCollection();
                collection.setId(id);
                collection.setIsPrint(ISCode.NO.getCode());
                seriesOrderCollectionMapper.updateById(collection);
            }

            SeriesOrderReceiptDetailsPreviewReq previewReq = new SeriesOrderReceiptDetailsPreviewReq();
            previewReq.setOrderId(receiptDetails.getOrderId());
            previewReq.setScheduleId(receiptDetails.getScheduleId());
            previewReq.setUserId(req.getUserId());
            previewReq.setDataSource(DataSourceCode.COLLECTION.getCode());
            previewReq.setIdList(dto.getCollectionIdList());
            Result<SeriesOrderReceiptDetailsPreviewDTO> previewResult = preview(previewReq);
            if (!previewResult.isSuccess()) {
                throw new BusinessException(SystemError.SYS_500);
            }

            dto = previewResult.getData();
            String dtoJsonString = JSON.toJSONString(dto);
            SeriesOrderReceiptDetailsAddReq addReq = JSON.parseObject(dtoJsonString, SeriesOrderReceiptDetailsAddReq.class);
            addReq.setUserId(req.getUserId());
            add(addReq);
        }
        return Result.success(dto);
    }

    /**
     * 作废
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result invalid(SeriesOrderReceiptInvalidReq req, TokenUser currentUser) {
        SeriesOrderReceiptDetails receiptDetails = getById(req.getId());
        if (receiptDetails == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        SeriesOrderReceipt dbReceipt = seriesOrderReceiptMapper.selectById(receiptDetails.getReceiptId());
        if (dbReceipt == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        if (Objects.equals(dbReceipt.getReceiptType(), ReceiptTypeCode.INSURANCE.getCode())) {
            throw new BusinessException(SeriesOrderErrorCode.INSURANCE_INVALID_LIMIT);
        }
        if (!Objects.equals(dbReceipt.getReceiptStatus(), ReceiptStatusCode.VALID.getCode())) {
            throw new BusinessException(SeriesOrderErrorCode.STATUS_ERROR);
        }

        LocalDateTime now = LocalDateTime.now();
        dbReceipt.setVoidTime(now);
        dbReceipt.setVoidReason(req.getVoidReason());
        dbReceipt.setGmtModified(now);
        dbReceipt.setModifiedId(currentUser.getId());
        dbReceipt.setReceiptStatus(ReceiptStatusCode.INVALID.getCode());
        seriesOrderReceiptMapper.updateById(dbReceipt);

        receiptDetails.setReceiptStatus(ReceiptStatusCode.INVALID.getCode());
        updateById(receiptDetails);

        //订单统计
        QueryWrapper<SeriesOrderReceiptTourist> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getReceiptId, dbReceipt.getId());
        queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getOrderId, dbReceipt.getOrderId());
        List<SeriesOrderReceiptTourist> receiptTouristList = seriesOrderReceiptTouristMapper.selectList(queryWrapper);

        //订单统计
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SeriesOrderAmountStatistics::getOrderId, dbReceipt.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper2);
        //已出单据金额
        BigDecimal orderReceiptedAmount = statistics.getReceiptedAmount();
        //游客统计
        for (SeriesOrderReceiptTourist receiptTourist : receiptTouristList) {
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(receiptTourist.getTouristId());
            if (touristInfo == null) {
                throw new BusinessException(SystemError.SYS_411);
            }
            if (Objects.equals(receiptTourist.getIsReceiptCalculated(), ISCode.YES.getCode())) {
                touristInfo.setIsReceiptCalculated(ISCode.NO.getCode());
            }
            //已出单据金额
            BigDecimal receiptedAmount = touristInfo.getReceiptedAmount().subtract(receiptTourist.getReceiptAmount());
            touristInfo.setReceiptedAmount(receiptedAmount);
            seriesOrderTouristInfoMapper.updateById(touristInfo);

            orderReceiptedAmount = orderReceiptedAmount.add(receiptedAmount);
        }

        if (StringUtils.isBlank(receiptDetails.getReceipJson())) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesOrderReceiptDetailsPreviewDTO dto = JSON.parseObject(receiptDetails.getReceipJson(), SeriesOrderReceiptDetailsPreviewDTO.class);
        if (dto == null) {
            return Result.failed(SystemError.SYS_411);
        }
        if (CollectionUtils.isEmpty(dto.getCollectionIdList())) {
            return Result.failed(SystemError.SYS_500);
        }

        //将收款明细设置成打印否
        for (Long id : dto.getCollectionIdList()) {
            SeriesOrderCollection collection = new SeriesOrderCollection();
            collection.setId(id);
            collection.setIsPrint(ISCode.NO.getCode());
            seriesOrderCollectionMapper.updateById(collection);
        }

        statistics.setReceiptedAmount(orderReceiptedAmount);
        seriesOrderAmountStatisticsMapper.updateById(statistics);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result invalidAll(SeriesOrderReceiptInvalidAllReq req) {
        QueryWrapper<SeriesOrderReceiptDetails> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.lambda().eq(SeriesOrderReceiptDetails::getOrderId, req.getOrderId());
        queryWrapper3.lambda().eq(SeriesOrderReceiptDetails::getReceiptType, ReceiptTypeCode.SALE.getCode());
        queryWrapper3.lambda().eq(SeriesOrderReceiptDetails::getReceiptStatus, ReceiptStatusCode.VALID.getCode());
        List<SeriesOrderReceiptDetails> receiptDetailsList = seriesOrderReceiptDetailsMapper.selectList(queryWrapper3);

        //订单统计
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SeriesOrderAmountStatistics::getOrderId, req.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper2);
        //已出单据金额
        BigDecimal orderReceiptedAmount = statistics.getReceiptedAmount();
        for (SeriesOrderReceiptDetails receiptDetails : receiptDetailsList) {
            SeriesOrderReceipt dbReceipt = seriesOrderReceiptMapper.selectById(receiptDetails.getReceiptId());
            if (dbReceipt == null) {
                return Result.failed(SystemError.SYS_411);
            }
            if (Objects.equals(dbReceipt.getReceiptStatus(), ReceiptStatusCode.INVALID.getCode())) {
                continue;
            }

            LocalDateTime now = LocalDateTime.now();
            dbReceipt.setVoidTime(now);
            dbReceipt.setVoidReason(req.getVoidReason());
            dbReceipt.setGmtModified(now);
            dbReceipt.setModifiedId(req.getUserId());
            dbReceipt.setReceiptStatus(ReceiptStatusCode.INVALID.getCode());
            seriesOrderReceiptMapper.updateById(dbReceipt);

            receiptDetails.setReceiptStatus(ReceiptStatusCode.INVALID.getCode());
            updateById(receiptDetails);

            QueryWrapper<SeriesOrderReceiptTourist> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getReceiptId, dbReceipt.getId());
            queryWrapper.lambda().eq(SeriesOrderReceiptTourist::getOrderId, dbReceipt.getOrderId());
            List<SeriesOrderReceiptTourist> receiptTouristList = seriesOrderReceiptTouristMapper.selectList(queryWrapper);
            //游客统计
            for (SeriesOrderReceiptTourist receiptTourist : receiptTouristList) {
                SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(receiptTourist.getTouristId());
                if (touristInfo == null) {
                    throw new BusinessException(SystemError.SYS_411);
                }
                //已出单据金额
                BigDecimal receiptedAmount = touristInfo.getReceiptedAmount().subtract(receiptTourist.getReceiptAmount());
                touristInfo.setReceiptedAmount(receiptedAmount);
                touristInfo.setIsReceiptCalculated(ISCode.NO.getCode());
                orderReceiptedAmount = orderReceiptedAmount.add(receiptedAmount);

                seriesOrderTouristInfoMapper.updateById(touristInfo);
            }

            if (StringUtils.isBlank(receiptDetails.getReceipJson())) {
                throw new BusinessException(SystemError.SYS_411);
            }
            SeriesOrderReceiptDetailsPreviewDTO dto = JSON.parseObject(receiptDetails.getReceipJson(), SeriesOrderReceiptDetailsPreviewDTO.class);
            if (dto == null) {
                throw new BusinessException(SystemError.SYS_411);
            }
            if (CollectionUtils.isEmpty(dto.getCollectionIdList())) {
                throw new BusinessException(SystemError.SYS_500);
            }

            //将收款明细设置成打印否
            for (Long id : dto.getCollectionIdList()) {
                SeriesOrderCollection collection = new SeriesOrderCollection();
                collection.setId(id);
                collection.setIsPrint(ISCode.NO.getCode());
                seriesOrderCollectionMapper.updateById(collection);
            }

        }
        //订单统计
        statistics.setReceiptedAmount(orderReceiptedAmount);
        seriesOrderAmountStatisticsMapper.updateById(statistics);


        QueryWrapper<SeriesOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
        queryWrapper.lambda().eq(SeriesOrderCollection::getIsPrint, ISCode.NO.getCode());
        queryWrapper.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SeriesOrderCollection> collectionList = seriesOrderCollectionMapper.selectList(queryWrapper);
        Set<Long> touristIdSet = new HashSet<>();
        for (SeriesOrderCollection collection : collectionList) {
            //游客id
            touristIdSet.add(collection.getTouristId());
        }
        List<Long> idList = new ArrayList<>(touristIdSet);

        SeriesOrderReceiptDetailsPreviewReq previewReq = new SeriesOrderReceiptDetailsPreviewReq();
        previewReq.setOrderId(req.getOrderId());
        previewReq.setScheduleId(req.getScheduleId());
        previewReq.setUserId(req.getUserId());
        previewReq.setDataSource(DataSourceCode.RECEIPT.getCode());
        previewReq.setIdList(idList);
        Result<SeriesOrderReceiptDetailsPreviewDTO> previewResult = preview(previewReq);
        if(!previewResult.isSuccess()) {
            return Result.failed(SystemError.SYS_500);
        }
        SeriesOrderReceiptDetailsPreviewDTO dto = previewResult.getData();
        String dtoJsonString = JSON.toJSONString(dto);
        SeriesOrderReceiptDetailsAddReq addReq = JSON.parseObject(dtoJsonString, SeriesOrderReceiptDetailsAddReq.class);
        addReq.setUserId(req.getUserId());
        add(addReq);

        return Result.success();
    }
}
